package com.newear.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.widget.ProgressBar;

import com.newear.R;
import com.newear.bean.VersionUpgrade;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 软件更新管理类
 * Created by josan_tang on 2016/8/15.
 */
public class UpdateSoftManager {
    private static final String TAG = "UpdateSoftManager";

    private ProgressBar mProgressBar;   //更新进度条
    private ProgressDialog updateSoftDialog;    //更新框
    private static Dialog softDialog;
    private Context context;
    private boolean cancelUpdate = false;   //取消状态
    private int progress = 0;   //进度


    private static final int UPDATE_DIALOG = 1; //更新进度条
    private static final int DOWNLOAD_FINISHED = 2; //下载完成

    private ArrayMap<String,Object> apkParam;   //apk的参数

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case UPDATE_DIALOG: //更新进度条
                        updateSoftDialog.setProgress(progress);
                        break;
                    case DOWNLOAD_FINISHED: //下载完成
                        //安装apk
                        installApk();
                        break;
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "Handler-handlerMessage-Exception!");
            }
        }
    };

    /**
     * 构造方法
     * @param context
     */
    public UpdateSoftManager(Context context, ArrayMap<String, Object> apkParam) {
        this.context = context;
        this.apkParam = apkParam;
    }

    /**
     * 显示更新对话框
     */
    public void showUpdateDialog() {
        updateSoftDialog = new ProgressDialog(context);
        updateSoftDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        updateSoftDialog.setTitle("Software online update");
        updateSoftDialog.setMessage("Downloading......");
        updateSoftDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置取消状态
                cancelUpdate = true;
            }
        });
        updateSoftDialog.setCanceledOnTouchOutside(false);
        updateSoftDialog.setMax(100);
        updateSoftDialog.setCancelable(true);
        updateSoftDialog.show();
        //开启异步任务，下载apk文件
        new DownloadAsyncTask().execute();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        try {
            //如果sd卡存在，并且具有读写权限
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //得到下载文件流
                URL url = new URL((String) apkParam.get("apkUrl"));
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.connect();
                int length = connection.getContentLength();
                InputStream inputStream = connection.getInputStream();

                //这里为空
                File apkFile = new File(MyConstant.apkPath, (String) apkParam.get("name"));
                if(apkFile.exists()) {
                    apkFile.delete();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(apkFile);
                int count = 0;
                byte buff[] = new byte[1024];
                while(!cancelUpdate) {
                    int numRead = inputStream.read(buff);
                    count += numRead;
                    progress = (int) ((float)count / length * 100);
                    mHandler.sendEmptyMessage(UPDATE_DIALOG);
                    if(numRead < 0) {
                        //下载完成
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISHED);
                        break;
                    }
                    fileOutputStream.write(buff, 0, numRead);
                }
                fileOutputStream.close();
                inputStream.close();
            }
        } catch (Exception e) {
            MyLogger.e(TAG, "downloadApk-Exception!");
        }
    }

    /**
     * 安装Apk包
     */
    private void installApk() {
        //设置为第一次启动，方便新版本打开3次提示评分
        File apkFile = new File(MyConstant.apkPath, (String) apkParam.get("name"));
        if(!apkFile.exists()) {
            return;
        }
        //通过Intent安装Apk文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),"application/vnd.android.package-archive");
        this.context.startActivity(intent);
    }

    /**
     * 下载任务
     */
    class DownloadAsyncTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {
            //下载apk
            downloadApk();
            return null;
        }
    }

    /**
     * 显示软件在线升级对话框
     */
    public static void showUpdateDialog(final Context mContext, final VersionUpgrade versionUpgrade) {
        softDialog = new AlertDialog.Builder(mContext)
                .setTitle("New Version Available!")
                .setMessage("A new version of the That's App is available. Would you like to upgrade?")
                .setPositiveButton("Upgrade", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        if (!HardWare.isNetworkAvailable(mContext)) {
                            T.shortToast(mContext, mContext.getResources().getString(R.string.please_check_network));
                            return ;
                        }
                        MySharedPreferences.getInstance().setUpdateApk(mContext, false);
                        ArrayMap<String, Object> arrayMap = new ArrayMap<>();
                        arrayMap.put("name", "thats" +versionUpgrade.getVersion() + ".apk");
                        arrayMap.put("apkUrl", versionUpgrade.getDownUrl());
                        new UpdateSoftManager(mContext,arrayMap).showUpdateDialog();
                    }
                })
                .setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dialog != null) {
                            MySharedPreferences.getInstance().setCurDayDontUpdate(mContext);
                            MySharedPreferences.getInstance().setUpdateApk(mContext, false);
                            dialog.dismiss();
                        }
                    }
                })
                .create();
        softDialog.show();
    }
}
